package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"zy19/models"
)

type UserController struct {
	beego.Controller
}

func (c *UserController) Register() {
	username := c.GetString("username")
	password := c.GetString("password")

	if username == "" || password == "" {
		c.Data["json"] = map[string]interface{}{
			"code": 0,
			"msg":  "不能为空",
		}
		c.ServeJSON()
		return
	}
	var user models.User
	models.DB.Debug().Where("username=?", username).Find(&user)
	if user.ID != 0 {
		c.Data["json"] = map[string]interface{}{
			"code": 0,
			"msg":  "用户已存在",
		}
		c.ServeJSON()
		return
	}
	users := models.User{
		Username: username,
		Password: password,
	}
	err := models.DB.Debug().Create(&users).Error
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 0,
			"msg":  "注册失败",
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "注册成功",
	}
	c.ServeJSON()
	return
}
func (c *UserController) Login() {
	username := c.GetString("username")
	password := c.GetString("password")

	if username == "" || password == "" {
		c.Data["json"] = map[string]interface{}{
			"code": 0,
			"msg":  "不能为空",
		}
		c.ServeJSON()
		return
	}
	var user models.User
	models.DB.Debug().Where("username=?", username).Find(&user)
	if user.ID != 0 {
		c.Data["json"] = map[string]interface{}{
			"code": 0,
			"msg":  "用户已存在",
		}
		c.ServeJSON()
		return
	}
	users := models.User{
		Username: username,
		Password: password,
	}
	err := models.DB.Debug().Find(&users).Error
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 0,
			"msg":  "登录失败",
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "登录成功",
	}
	c.ServeJSON()
	return
}
